package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.mail.internet.AddressException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.formatter.IllegalMessageException;
import com.conversationboard.model.NoSuchThreadException;
import com.conversationboard.model.Thread;
import com.conversationboard.model.User;

@WebServlet(name = "AdminMoveThreadControllerServlet", urlPatterns = "/Admin/AdminMoveThreadControllerServlet")
public class AdminMoveThreadControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -210163328547328288L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		int boardId = Integer.parseInt(request.getParameter("boardid"));
		int threadId = Integer.parseInt(request.getParameter("threadid"));
		int targetBoardId = Integer.parseInt(request.getParameter("targetboardid"));

		try {

			/* Ensure you have authority */

			String loginId = request.getUserPrincipal().getName();
			User user = User.get(loginId);

			if (user.isSiteAdmin() || (user.isBoardAdmin(boardId) && user.isBoardAdmin(targetBoardId))) {

				Thread thread = Thread.get(boardId, threadId);
				thread.moveToBoard(user, targetBoardId);

				response.sendRedirect(request.getContextPath() + "/NewAnswersControllerServlet?boardid=" + targetBoardId);

			} else {

				request.setAttribute("message", "You are not authorised to perform that operation");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

		} catch (NoSuchThreadException e) {
			throw new ServletException(e);
		} catch (IllegalMessageException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (AddressException e) {
			throw new ServletException(e);
		}

	}

}
